# -*- coding: utf-8 -*-
from odoo import api, fields, models, tools


class QualityCheck(models.Model):
    _name = "quality.check"
    _description = 'Quality Check'

    name = fields.Char(u'方案名称', required=True)
    para_lines = fields.One2many('qc.mid', 'qc_id', u'质检行', required=True)

    # para_a = fields.Many2one('QcPara','参数')
    # sqma_id = fields.Many2many('stock.quality.manage','order_line',u'质检名称')


class QcPara(models.Model):
    _name = "qc.para"
    _description = "Quality Check parameter"

    para = fields.Char(u'质检参数', required=True)
    standard_value = fields.Char(u'实际值2')
    up_value = fields.Float(u'上限', required=True)
    low_value = fields.Float(u'下限', required=True)
    _sql_constraints = [('cons_qc_para_name', 'UNIQUE(para)', U'参数已存在，请重新设置！')]

    @api.multi
    def name_get(self):
        res = []
        for prl in self:
            res.append((prl.id, prl.para))
        return res


class QcMid(models.Model):
    _name = "qc.mid"
    _description = "Quality Check Middle table"
    _order = "sequence"

    qp_id = fields.Many2one('qc.para', '参数名称')

    @api.onchange('qp_id')
    def _onchange_para(self):
        if self.qp_id:
            self._cr.execute(
                """SELECT up_value,low_value,standard_value FROM qc_para WHERE para =\'%s\' """ %
                self.qp_id.name_get()[0][1])
            rlist = self._cr.fetchall()
            # self.standard_value = rlist[0][0]
            self.up_value = rlist[0][0]
            self.low_value = rlist[0][1]
            self.standard_value = rlist[0][2]

    standard_value = fields.Char(u'实际值2')
    qc_id = fields.Many2one('quality.check', store=True)
    up_value = fields.Float(u'上限', required=True)
    low_value = fields.Float(u'下限', required=True)
    sequence = fields.Integer()

# class QcMid(models.Model):
#     _name = "qc.mid"
#     _description = "Quality Check Middle table"
#
#     def func_para(self):
#         self._cr.execute("""select para from qc_para""")
#         res = self._cr.fetchall()
#         return [(str(key), val) for key, val in enumerate(res)]
#
#     @api.onchange('para')
#     def _onchange_para(self):
#         strA = None
#         for dic in self.func_para():
#             if dic[0] == self.para:
#                 strA = dic[1][0]
#         if self.para:
#             self._cr.execute(
#                 """SELECT standard_value FROM qc_para WHERE para =\'%s\' """ % strA)
#             res = self._cr.fetchall()[0][0]
#             self.standard_value = res
#
#     para = fields.Selection(func_para)
#     qc_id = fields.Many2one('quality.check', store=True)
#     standard_value = fields.Float(u'参数值')
